package com.youku.component.report;

import static org.junit.Assert.assertNotNull;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

public class ReportHolder {

	private static Map<String, TestReport> reportHolder = new HashMap<>();

	private static final Map<String, Class<?>> displays;

	static {
		displays = new HashMap<>();
		displays.put("html", HtmlTestReport.class);
		displays.put("txt", TextTestReport.class);
	}

	public static void bindReportDisplayWithProject(String projectId, String display) {
		display = StringUtils.isBlank(display) ? "html" : display;
		TestReport report = null;
		Class<?> targetClass = displays.get(display);
		try {
			report = (TestReport) targetClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			throw new RuntimeException("初始化"+targetClass.getName()+"类型失败",e);
		}
		if (report == null)
			throw new IllegalArgumentException("不支持" + display + "格式的报告");

		reportHolder.put(projectId, report);
	}

	/**
	 * 为报表添加一行记录
	 * 
	 * @param projectId
	 * @param record
	 */
	public static void addRecordForReport(TestRecord record) {
		TestReport report = reportHolder.get(record.getProjectId());
		assertNotNull("项目id错误", report);

		report.setProjectId(record.getProjectId());
		report.addTestRecord(record);
		reportHolder.put(record.getProjectId(), report);
	}

	/**
	 * 获取报告
	 * 
	 * @param projectId
	 * @return
	 */
	public static TestReport getReport(String projectId) {
		return reportHolder.get(projectId);
	}

	public static List<TestReport> getAllReports() {
		List<TestReport> testReports = new LinkedList<>();

		for (Entry<String, TestReport> entry : reportHolder.entrySet()) {
			testReports.add(entry.getValue());
		}

		return testReports;
	}

}
